import { defineComponent, h, onMounted } from "vue";
import type {PropType} from "vue";
import type { MenuTree } from "@/types/menu";
import * as ElementPlusIconsVue from "@element-plus/icons";

/**
 * 获得第一个可以被选择的
 * @param mainTree 菜单
 */
export function getFirstMenu(mainTree: MenuTree): MenuTree | null {
  function search(tree: MenuTree): MenuTree | null {
    let sortedChildren = tree.children.sort(
      (a, b) => (a.sort ?? 0) - (b.sort ?? 0)
    );
    for (let menu of sortedChildren) {
      if (menu.children.length != 0) {
        // 继续循环
        let res = search(menu);
        if (res) {
          return res;
        }
      } else {
        return menu;
      }
    }
    return null;
  }

  return search(mainTree);
}

export default defineComponent({
  props: {
    menu: {
      type: Object as PropType<MenuTree>,
    },
    choose: {
      type: Function,
    },
  },
  components: {
    ...ElementPlusIconsVue,
  },
  name: "MenuItemTree",
  setup() {

  },
  render() {
    const { menu, choose } = this;
    function selectMenu(menu: MenuTree) {
      if (choose) {
        choose(menu);
      }
    }

    if (menu == undefined) {
      return <div></div>;
    }

    // 菜单
    function renderMenu(menu: MenuTree) {
      const slots = {
        title: () => (
          menu.hidden?"":   
          <div class="menuTreeBox">
            <el-icon>{menu.meta.icon && h(ElementPlusIconsVue[menu.meta.icon])}</el-icon>
              <span class={"menutype" + menu.type}>
                {menu.meta.title}
              </span>
          </div>
        ),
        default: () =>
          menu.children.map((t) => {
            return renderMenu(t);
          }),
      };

      if (menu.children.length == 0) {
        return (
          menu.hidden?'':
          <el-menu-item
            index={menu.path}
            v-slots={slots}
            onClick={() => selectMenu(menu)}
          ></el-menu-item>
        );
      } else {
        return  menu.hidden?'':<el-sub-menu index={menu.path} v-slots={slots}></el-sub-menu>;
      }
    }

    return renderMenu(menu);
  },
});
